/**
 * 前后端统一的数据验证规则
 * 确保前端验证规则与后端完全一致
 */

// 验证规则常量
export const VALIDATION_RULES = {
  // 用户名规则
  USERNAME: {
    MIN_LENGTH: 3,
    MAX_LENGTH: 20, // 与后端保持一致
    PATTERN: /^[a-zA-Z0-9_]+$/, // 只能包含字母、数字、下划线
    PATTERN_MESSAGE: '用户名只能包含字母、数字和下划线'
  },
  
  // 密码规则
  PASSWORD: {
    MIN_LENGTH: 6,
    MAX_LENGTH: 20,
    PATTERN: /^(?=.*[a-zA-Z])(?=.*\d).*$/, // 必须包含字母和数字
    PATTERN_MESSAGE: '密码必须包含字母和数字'
  },
  
  // 邮箱规则
  EMAIL: {
    PATTERN: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    PATTERN_MESSAGE: '邮箱格式不正确'
  },
  
  // 真实姓名规则
  REAL_NAME: {
    MAX_LENGTH: 50
  }
}

// 验证函数
export const validators = {
  /**
   * 验证用户名
   */
  username: (value: string): string | null => {
    if (!value || value.trim() === '') {
      return '请输入用户名'
    }
    
    const trimmedValue = value.trim()
    
    if (trimmedValue.length < VALIDATION_RULES.USERNAME.MIN_LENGTH) {
      return `用户名长度不能少于${VALIDATION_RULES.USERNAME.MIN_LENGTH}个字符`
    }
    
    if (trimmedValue.length > VALIDATION_RULES.USERNAME.MAX_LENGTH) {
      return `用户名长度不能超过${VALIDATION_RULES.USERNAME.MAX_LENGTH}个字符`
    }
    
    if (!VALIDATION_RULES.USERNAME.PATTERN.test(trimmedValue)) {
      return VALIDATION_RULES.USERNAME.PATTERN_MESSAGE
    }
    
    return null
  },

  /**
   * 验证密码
   */
  password: (value: string): string | null => {
    if (!value || value.trim() === '') {
      return '请输入密码'
    }
    
    if (value.length < VALIDATION_RULES.PASSWORD.MIN_LENGTH) {
      return `密码长度不能少于${VALIDATION_RULES.PASSWORD.MIN_LENGTH}个字符`
    }
    
    if (value.length > VALIDATION_RULES.PASSWORD.MAX_LENGTH) {
      return `密码长度不能超过${VALIDATION_RULES.PASSWORD.MAX_LENGTH}个字符`
    }
    
    if (!VALIDATION_RULES.PASSWORD.PATTERN.test(value)) {
      return VALIDATION_RULES.PASSWORD.PATTERN_MESSAGE
    }
    
    return null
  },

  /**
   * 验证邮箱
   */
  email: (value: string): string | null => {
    if (!value || value.trim() === '') {
      return '请输入邮箱地址'
    }
    
    const trimmedValue = value.trim()
    
    if (!VALIDATION_RULES.EMAIL.PATTERN.test(trimmedValue)) {
      return VALIDATION_RULES.EMAIL.PATTERN_MESSAGE
    }
    
    return null
  },

  /**
   * 验证真实姓名
   */
  realName: (value: string): string | null => {
    if (!value) return null // 真实姓名是可选的
    
    const trimmedValue = value.trim()
    
    if (trimmedValue.length > VALIDATION_RULES.REAL_NAME.MAX_LENGTH) {
      return `真实姓名长度不能超过${VALIDATION_RULES.REAL_NAME.MAX_LENGTH}个字符`
    }
    
    return null
  },

  /**
   * 验证确认密码
   */
  confirmPassword: (value: string, originalPassword: string): string | null => {
    if (!value || value.trim() === '') {
      return '请确认密码'
    }
    
    if (value !== originalPassword) {
      return '两次输入的密码不一致'
    }
    
    return null
  }
}

// Element Plus 表单验证规则
export const getElementPlusRules = () => {
  return {
    // 登录表单验证规则
    login: {
      username: [
        { required: true, message: '请输入用户名或邮箱', trigger: 'blur' },
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            // 登录时可以是用户名或邮箱，所以验证规则更宽松
            if (!value || value.trim() === '') {
              callback(new Error('请输入用户名或邮箱'))
              return
            }
            
            const trimmedValue = value.trim()
            
            // 如果包含@符号，按邮箱验证
            if (trimmedValue.includes('@')) {
              const emailError = validators.email(trimmedValue)
              if (emailError) {
                callback(new Error(emailError))
                return
              }
            } else {
              // 否则按用户名验证
              const usernameError = validators.username(trimmedValue)
              if (usernameError) {
                callback(new Error(usernameError))
                return
              }
            }
            
            callback()
          },
          trigger: 'blur'
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            const error = validators.password(value)
            if (error) {
              callback(new Error(error))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    },

    // 注册表单验证规则
    register: {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            const error = validators.username(value)
            if (error) {
              callback(new Error(error))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            const error = validators.email(value)
            if (error) {
              callback(new Error(error))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            const error = validators.password(value)
            if (error) {
              callback(new Error(error))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' }
      ],
      realName: [
        { 
          validator: (_rule: any, value: string, callback: Function) => {
            const error = validators.realName(value)
            if (error) {
              callback(new Error(error))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
  }
}

/**
 * 处理后端验证错误
 * 将后端返回的字段错误映射到前端表单
 */
export interface ValidationError {
  field: string
  message: string
}

export const handleBackendValidationErrors = (errors: Record<string, string>): ValidationError[] => {
  return Object.entries(errors).map(([field, message]) => ({
    field,
    message
  }))
}

/**
 * 显示字段级别的错误提示
 * 用于在表单字段下方显示后端返回的具体错误信息
 */
export const showFieldErrors = (formRef: any, errors: ValidationError[]) => {
  if (!formRef) return
  
  // 清除之前的错误
  formRef.clearValidate()
  
  // 设置字段错误
  errors.forEach(({ field, message }) => {
    formRef.setFields({
      [field]: {
        message,
        field
      }
    })
  })
}
